// 设置ajax的 全局配置
$.ajaxSetup({
  error: function (result) {
    if (result.responseJSON && result.responseJSON.message) {
      if (result.responseJSON.message == 'JWT expired') {
        alert('token过期,请重新登录')
      }
    }
  }
});

//const codeList = localStg.get('codelistOrigin') || []
//const userGroup = codeList.find(item => item.codeversion === 'xzqh' && item.grade === 3)

let divisionCode = '330522'
let divisionName = 'UNKNOW'

/*if (userGroup) {
  divisionCode = userGroup.code
  divisionName = userGroup.name
}*/

var requestApiUrl = {
  homeInfo: '/house_extended',
  keyInfoExpect: '/key_extended_with_stats_for_last_30day_midnight_gapped', //夜间异常活动
  personInfo: '/user_extended_with_stats_for_last_30day', //住所频繁更换
  moreAddressInfo: '/user_extended_with_stats_for_active_formal', //一人多处住所
  LandlordInfo: '/lock',                 //房东信息
  LandlordInfo2: '/operation',                 //房东拥有房间总数（包含不同地址）
  CheckInPerson: '/key',                  //  当前入住的人员情况

}

var houseInfo = {
  total: [0, 0, 0, 0, 0],  // 房的5个tab 各自的总页数
  nameList: ['一房多人', '短期没有使用', '夜间频繁使用', '访客来访频繁居住', '更换房客频繁'],
  totalDomId: ['manyPeoleInAHouseTotal', 'unusedInShortTimeTotal', 'frequentUseInNightTotal', 'frequentVisitorsTotal', 'frequentReplacementOfTenantsTotal'],
  ajaxUrl: [
    pgApiUtils(optimizedBaseUrl + requestApiUrl.homeInfo)
      .setRequestUrl('select=simpleaddr,lockid,housenumber,stats_per_lock_for_active_formal&stats_per_lock_for_active_formal->tally_users=gte.5&category=eq.long-term-rental&lockid=not.is.null&')
      .likeVal(`xzqhdm:${divisionCode}`)
      .order('xzqhdm,simpleaddr,housenumber'),
    pgApiUtils(optimizedBaseUrl + requestApiUrl.homeInfo)
      .setRequestUrl('category=eq.long-term-rental&limit=12&select=lockid,simpleaddr,housenumber,stats_per_lock_for_active_formal,stats_per_lock_event_for_active_formal&stats_per_lock_event_for_active_formal->>last_open_at=lte.' + new Date().format("yyyy-MM-dd") + '&lockid=not.is.null&')
      .likeVal(`xzqhdm:${divisionCode}`)
      .order('xzqhdm,simpleaddr,housenumber'),
    pgApiUtils(optimizedBaseUrl + requestApiUrl.homeInfo)    //3
      .setRequestUrl('select=lockid,simpleaddr,housenumber,stats_per_lock_for_active_formal,tally_per_lock_event_for_active_formal_today&tally_per_lock_event_for_active_formal_last_3day_midnight=gte.10&category=eq.long-term-rental&lockid=not.is.null&')
      .likeVal(`xzqhdm:${divisionCode}`)
      .order('xzqhdm,simpleaddr,housenumber'),
    pgApiUtils(optimizedBaseUrl + requestApiUrl.homeInfo)   //4
      .setRequestUrl('select=lockid,simpleaddr,housenumber,stats_per_lock_for_informal_last_7day&stats_per_lock_for_informal_last_7day->tally_users=gte.3&category=eq.long-term-rental&lockid=not.is.null&')
      .likeVal(`xzqhdm:${divisionCode}`)
      .order('xzqhdm,simpleaddr,housenumber'),
    pgApiUtils(optimizedBaseUrl + requestApiUrl.homeInfo)   //5
      .setRequestUrl('select=lockid,simpleaddr,housenumber,stats_per_lock_for_formal_last_15day&stats_per_lock_for_formal_last_15day->tally_user_sessions=gte.3&category=eq.long-term-rental&lockid=not.is.null&')
      .likeVal(`xzqhdm:${divisionCode}`)
      .order('xzqhdm,simpleaddr,housenumber'),
  ],// ajax路径
  ajaxUrlTotal:[
    pgApiUtils(optimizedBaseUrl + requestApiUrl.homeInfo)
      .setRequestUrl('select=housenumber&stats_per_lock_for_active_formal->tally_users=gte.5&category=eq.long-term-rental&lockid=not.is.null&')
      .likeVal(`xzqhdm:${divisionCode}`)
      .order('xzqhdm,simpleaddr,housenumber'),
    pgApiUtils(optimizedBaseUrl + requestApiUrl.homeInfo)
      .setRequestUrl('category=eq.long-term-rental&limit=12&select=housenumber&stats_per_lock_event_for_active_formal->>last_open_at=lte.' + new Date().format("yyyy-MM-dd") + '&lockid=not.is.null&')
      .likeVal(`xzqhdm:${divisionCode}`)
      .order('xzqhdm,simpleaddr,housenumber'),
    null,
    null,
    pgApiUtils(optimizedBaseUrl + requestApiUrl.homeInfo)
      .setRequestUrl('select=housenumber&stats_per_lock_for_formal_last_15day->tally_user_sessions=gte.3&category=eq.long-term-rental&lockid=not.is.null&')
      .likeVal(`xzqhdm:${divisionCode}`)
      .order('xzqhdm,simpleaddr,housenumber'),
  ],
  cacheList: {
    manyPeoleInAHouseTable: {},
    unusedInShortTimeTable: {},
    frequentUseInNightTable: {},
    frequentVisitorsTable: {},
    frequentReplacementOfTenantsTable: {}
  },
  ajaxIndex: {
    manyPeoleInAHouseTable: 0,
    unusedInShortTimeTable: 1,
    frequentUseInNightTable: 2,
    frequentVisitorsTable: 3,
    frequentReplacementOfTenantsTable: 4
  },
  tables: [
    [0, 1],
    [0, 1],
    [0, 1],
    [0, 1],
    [0, 1]
  ],
  exportHandler: [
    function (response) {           //1
      for (let i = 0; i < response.length; i++) {
        delete response[i].lockid
        //response[i].tally_keys = response[i].stats_per_lock_for_active_formal.tally_keys
        response[i].tally_users = response[i].stats_per_lock_for_active_formal.tally_users
        delete response[i].stats_per_lock_for_active_formal
      }

      return response || []

    },
    function (response) {           //2
      for (let i = 0; i < response.length; i++) {
        delete response[i].lockid
        time = response[i].stats_per_lock_event_for_active_formal.last_open_at
        time = time.replace("T", "  ")
        response[i].stats_per_lock_event_for_active_formal.last_open_at = time
        if (response[i].stats_per_lock_event_for_active_formal == null) {
          response[i].last_open_at = '-';
        } else {
          response[i].tally_keys = response[i].stats_per_lock_for_active_formal.tally_keys
          response[i].last_open_at = response[i].stats_per_lock_event_for_active_formal.last_open_at
          delete response[i].stats_per_lock_event_for_active_formal
          delete response[i].stats_per_lock_for_active_formal
        }
      }
      return response || [];
    },
    function (response) {           //3
      for (let i = 0; i < response.length; i++) {
        delete response[i].lockid
        response[i].tally_keys = response[i].stats_per_lock_for_active_formal.tally_keys
        delete response[i].stats_per_lock_for_active_formal
      }
      return response || []

    },
    function (response) {           //4
      for (let i = 0; i < response.length; i++) {
        delete response[i].lockid
       response[i].tally_users = response[i].stats_per_lock_for_informal_last_7day.tally_users|| 0
        delete response[i].stats_per_lock_for_informal_last_7day

      }
      return response || []
    },
    function (response) {           //5
      for (let i = 0; i < response.length; i++) {
        delete response[i].lockid
        response[i].tally_granted_keys = response[i].stats_per_lock_for_formal_last_15day.tally_granted_keys || 0
        response[i].tally_revoked_keys = response[i].stats_per_lock_for_formal_last_15day.tally_revoked_keys || 0
        response[i].tally_user_sessions = response[i].stats_per_lock_for_formal_last_15day.tally_user_sessions
        delete response[i].stats_per_lock_for_formal_last_15day
      }
      return response
    }
  ],
  sheetHeader: [
    ['房间地址', '房间号', '在住人数'],
    ['房间', '房间号', '钥匙数量', '最近一次开门时间'],
    ['房间地址', '房间号', '钥匙数量', '当日开门总数'],
    ['房间地址', '房间号', '当前周期内发放总数'],
    ['房间地址', '房间号', '发放钥匙数量', '失效钥匙数量', '当前有效钥匙数量']
  ],
  columnWidths: [
    [400, 200, 200],
    [200, 200, 150, 300],
    [400, 200, 200, 200],
    [600, 200, 200],
    [400, 200, 200, 200, 200]
  ],
  bindEvent:new Array(5),
};

//$().DataTable.ext.internal._fnFeatureHtmlPaginate
//$().DataTable.ext.internal._fnPageChange()
var personInfo = {
  total: [0, 0, 0],  // 人的3个tab 各自的总页数
  nameList: ['夜间异常活动总数', '频繁换房人员', '一人多处住所'],
  totalDomId: ['nocturnalAbnormalActivityTotal', 'frequentRoomChangersTotal', 'manyRoomsForOneCertificateTotal'],
  ajaxUrl: [
    pgApiUtils(optimizedBaseUrl + requestApiUrl.keyInfoExpect)  //6夜间异常活动
      .setRequestUrl('select=lockid,keyid,name,phone,detailaddr,housenumber&category=eq.long-term-rental&tally_dates=gte.3&lockid=not.is.null&')
      .likeVal('xzqhdm:330522*'),

    pgApiUtils(optimizedBaseUrl + requestApiUrl.personInfo)    //7住所频繁更换
      .setRequestUrl('select=name,phones,identifier,tally_house_sessions&tally_house_sessions=gte.5&')
      .likeVal('key_details->0->>xzqhdm:330522*'),

    pgApiUtils(optimizedBaseUrl + requestApiUrl.moreAddressInfo)  //8一人
      .setRequestUrl('select=name,phones,identifier,tally_houses&tally_houses=gte.5&')
      .likeVal('key_details->0->>xzqhdm:330522*'),
  ],// ajax路径
  cacheList: {
    nocturnalAbnormalActivityTable: {},
    frequentRoomChangersTable: {},
    manyRoomsForOneCertificateTable: {}
  },
  ajaxIndex: {
    nocturnalAbnormalActivityTable: 0,
    frequentRoomChangersTable: 1,
    manyRoomsForOneCertificateTable: 2
  },
  tables: [
    [0, 1],
    [0, 1 , 2],
    [0, 1]
  ],
  exportHandler: [
    function (response) {
      for (let i = 0; i < response.length; i++) {
        delete response[i].lockid
        delete response[i].keyid
      }
      return response || []
    },
    function (response) {
      for (let i = 0; i < response.length; i++) {
        delete response[i].identifier
      }
      return response || [];
    },
    function (response) {
      for (let i = 0; i < response.length; i++) {
        delete response[i].identifier
      }
      return response || [];
    }
  ],
  sheetHeader: [
    ['姓名', '联系方式', '地址','房间号'],  //6
    ['姓名', '联系方式', '变动房间数量' ],  //7
    ['姓名', '联系方式', '入住房间数量'],  //8
  ],
  columnWidths: [
    ['200', '400', '600', '300'],
    [200, 400, 300],
    [200, 400, 600, 200]
  ],
  bindEvent:new Array(3)
};


function btn_export(index,isPerson) {
  var configInfo = isPerson ? personInfo : houseInfo
  $('#loadingBox').show()
  $.ajax({
    type: 'GET',
    //console.log('btn_export',btn_export(index,isPerson)),

    url:  configInfo.ajaxUrl[index].page(1,200),
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', tokenPgAuth);
      xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
    },
    contentType: 'application/json;chart-set=utf-8',
    dataType: 'json',
    success: function(response, b, xhr) {
      // 列标题，逗号隔开，每一个逗号就是隔开一个单元格
      response = configInfo.exportHandler[index](response)
      JsonToExcel(response,configInfo.nameList[index],'sheet',configInfo.sheetHeader[index],configInfo.columnWidths[index],)
      $('#loadingBox').hide()
    },
    error: function(data, b, c) {
      $('#loadingBox').hide()
      alert('导出出错')
    }
  })
}

function JsonToExcel(jsonData,fileName,sheetName,sheetHeader,columnWidths) {
  var option = {};
  option.fileName = fileName;
  console.log(columnWidths)
  option.datas = [
    {
      sheetData : jsonData,
      sheetName : sheetName,
      sheetHeader : sheetHeader,
      columnWidths: columnWidths,
    }
  ];
  var toExcel=new ExportJsonExcel(option);
  toExcel.saveExcel();
}

